import 'package:flutter/material.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/my_get_it.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/my_optimize_utils.dart';
import 'package:hxdj/message/rongcloud/rc_chat/controller/rc_chat_base_input_controller.dart';
import 'package:hxdj/message/rongcloud/rc_chat/controller/rc_chat_controller.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_global_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/widget/rc_chat_input_widget.dart';
import 'package:hxdj/message/rongcloud/rc_chat/config/rc_chat_config.dart';
import 'package:hxdj/message/rongcloud/chat/tim_uikit_history_message_list_container.dart';
import 'package:hxdj/message/rongcloud/chat/tim_uikit_text_field_controller.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_separate_view_model.dart';
import 'package:provider/provider.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

// 聊天页面
class RCChatPage extends StatefulWidget {
  final String targetId;

  static String routeName = "/RCChatPage";

  const RCChatPage({super.key, required this.targetId});

  @override
  State<RCChatPage> createState() => _RCChatPageState();
}

class _RCChatPageState extends State<RCChatPage> {
  bool isInit = false;

  //聊天的公共配置
  final RCChatGlobalModel globalModel = serviceLocator<RCChatGlobalModel>();

  //输入框的控制器
  final RCChatInputTextFieldController textFieldController = RCChatInputTextFieldController();

  late RCChatSeparateViewModel separateViewModel;

  late RCChatController chatController;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    separateViewModel = RCChatSeparateViewModel(widget.targetId);

    //聊天控制器
    chatController = RCChatController(viewModel: separateViewModel);
  }

  @override
  void didUpdateWidget(RCChatPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.targetId != oldWidget.targetId) {
      isInit = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    final isBuild = isInit;
    isInit = true;

    return RCChatProviderScope(
        separateViewModel: separateViewModel,
        conversationID: widget.targetId,
        controller: chatController,
        isBuild: isBuild,
        builder: (BuildContext oContext, RCChatSeparateViewModel separateViewModel, Widget? child) {
          return MyTapWidget(
            onTap: () {
              textFieldController.hideAllPanel();
            },
            child: Scaffold(
                resizeToAvoidBottomInset: false,
                backgroundColor: MyColours.bgColor,
                appBar: const MyAppBar(
                  title: "聊天",
                  backgroundColor: Colors.white,
                ),
                body: Stack(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                            child: Container(
                          color: MyColours.bgColor,
                          child: Align(
                              key: GlobalKey(),
                              alignment: Alignment.topCenter,
                              child: Listener(
                                onPointerMove: MyOptimizeUtils.throttle((_) => textFieldController.hideAllPanel(), 60),
                                child: TIMUIKitHistoryMessageListContainer(
                                  key: GlobalKey(),
                                  conversationID: widget.targetId,
                                ),
                              )),
                        )),
                        ChatInputWidget(textFieldController: textFieldController, chatController: chatController),
                      ],
                    ),
                  ],
                )),
          );
        });
  }
}

class RCChatProviderScope extends StatelessWidget {
  final RCChatGlobalModel globalModel = serviceLocator<RCChatGlobalModel>();

  final Widget? child;
  final RCChatSeparateViewModel separateViewModel;

  /// You could get the model from here, and transfer it to other widget from TUIKit.
  final Widget Function(BuildContext, RCChatSeparateViewModel, Widget?) builder;

  /// `RCChatController` needs to be provided if you use it outside.
  final RCChatController? controller;

  /// The global config for TIMUIKitChat.
  final RCChatConfig? config;

  /// Conversation id, use for get history message list.
  final String conversationID;

  /// The controller for text field.
  final TIMUIKitInputTextFieldController? textFieldController;

  final bool? isBuild;

  final AutoScrollController? scrollController;

  RCChatProviderScope(
      {super.key,
      this.child,
      this.textFieldController,
      required this.builder,
      this.isBuild,
      required this.conversationID,
      this.controller,
      this.config,
      this.scrollController,
      required this.separateViewModel}) {
    if (isBuild ?? false) {
      return;
    }
    controller?.model = separateViewModel;
    controller?.textFieldController = textFieldController;
    controller?.scrollController = scrollController;
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: separateViewModel),
        ChangeNotifierProvider.value(value: globalModel),
        Provider(create: (_) => RCChatConfig()),
      ],
      child: child,
      builder: (context, w) => builder(context, separateViewModel, w),
    );
  }
}


/*8


 return BasePage<RCChatViewModel>(
        onModelReady: (model) {
          viewModel = model;
          model.setSessionId(widget.targetId);
        },
        viewModel: RCChatViewModel(),
        builder: (BuildContext context, RCChatViewModel? model, Widget? child) {
          return Scaffold(
              resizeToAvoidBottomInset: false,
              backgroundColor: const Color.fromARGB(255, 245, 245, 245),
              appBar: const MyAppBar(
                title: "聊天",
                backgroundColor: Colors.white,
              ),
              body: MyTapWidget(
                onTap: () {
                  //隐藏所有面板
                  textFieldController.hideAllPanel();
                },
                child: Stack(children: [
                  Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Expanded(
                        child: Container(
                            color: MyColours.bgColor,
                            child: Align(
                                key: GlobalKey(),
                                alignment: Alignment.topCenter,
                                child: Listener(
                                    onPointerMove:
                                        MyOptimizeUtils.throttle((_) => textFieldController.hideAllPanel(), 60),
                                    child: RCChatMessageListSelector(
                                        conversationID: model!.targetId,
                                        builder: (context, messageList, child) {
                                          return RCChatMessageBasePage(
                                            viewModel: model,
                                            onLoadMore: (int? lastTimestamp) async {
                                              return model.getMessages(timestamp: lastTimestamp);
                                            },
                                            itemBuilder: (context, messageModel) {
                                              return LayoutBuilder(
                                                builder: (context, constraints) =>
                                                    ChatMessageBaseWidget(messageModel: messageModel!),
                                              );
                                            },
                                          );
                                        }))))),
                    
                  ])
                ]),
              ));
        });
*/